<template>
  <el-dialog
    v-model="dialogShow"
    :close-on-click-modal="false"
    custom-class="mydialog"
    width="50%"
    :title="title"
    @closed="close"
  >
    <el-form
      ref="formRef"
      :model="form"
      :label-width="formLabelWidth"
      size="small"
      :rules="rules"
    >
      <el-row>
        <el-col
          v-if="title=='编辑市场准入'"
          :span="12"
        >
          <el-form-item
            label="市场准入编号"
            prop="chanceNo"
          >
            <el-input
              v-model="form.chanceNo"
              disabled
              clearable
              placeholder="请输入市场准入编号"
              autocomplete="off"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="市场准入名称"
            prop="chanceName"
          >
            <el-input
              v-model="form.chanceName"
              clearable
              placeholder="请输入市场准入名称"
              autocomplete="off"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="准入模式"
            prop="accessMode"
          >
            <el-select
              v-model="form.accessMode"
              style="width: 100%"
              placeholder="请选择准入模式"
              clearable
            >
              <el-option
                v-for="item in accessOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="准入地区"
            prop="areas"
          >
            <el-cascader
              ref="cascader"
              v-model="form.areas"
              :popper-append-to-body="false"
              style="width: 100%"
              :options="citys"
              :props="props1"
              placeholder="请选择地区"
              collapse-tags
              clearable
              @change="areaChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="适用终端"
            prop="terminalType"
          >
            <el-select
              v-model="form.terminalType"
              style="width: 100%"
              placeholder="请选择适用终端"
              clearable
            >
              <el-option
                v-for="item in appOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="产品名称"
            prop="productName"
          >
            <product-popover
              ref="productPopover"
              :searchs="form.productName"
              @confirm="productConfirm"
              :disabled="disabled"
            >
              <el-input
                v-model="form.productName"
                placeholder="请输入产品名称"
                clearable
                @input="onInput"
                @clear="productClear"
              />
            </product-popover>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="批准文号"
            prop="productNum"
          >
            <el-input
              v-model="form.productNum"
              placeholder="请选择批准文号"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="包装规格"
            prop="packSpecs"
          >
            <el-input
              v-model="form.packSpecs"
              placeholder="请选择包装规格"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
                  label="生产厂家"
                  prop="producer"
          >
            <el-input
                    v-model="form.producer"
                    placeholder="请选择生产厂家"
                    disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="价格属性"
            prop="priceProperty"
          >
            <el-select
              v-model="form.priceProperty"
              style="width: 100%"
              placeholder="请选择价格属性"
              clearable
            >
              <el-option
                v-for="item in priceOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="终端价"
            prop="terminalPrice"
          >

            <price-input
              v-model:data="form.terminalPrice"
              placeholder="请输入终端价"
              is-unit
              :unit-str="form.sellUnit ? '元/' + getLabel('sell_unit',form.sellUnit) : ''"
            />

          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="市场准入结束日期"
            prop="expireTime"
          >
            <date-picker
              v-model:date="form.expireTime"
              clearable
              style="width: 100%;"
              :placeholder="`请选择日期`"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="其他描述"
            prop="remark"
          >
            <el-input
              v-model="form.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入内容"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="相关附件"
            prop="attachFiles"
          >
            <upload-file-view
              ref="uploadFileView"
              v-model:fileArr="form.attachFiles"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          class="border-btn"
          size="small"
          @click="close"
        >取消</el-button>
        <el-button
          class="main-btn"
          size="small"
          type="primary"
          @click="confirm"
        >提交审核</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import area from '@/utils/area.js'
import {defineComponent, getCurrentInstance, inject, onMounted, reactive, ref,} from 'vue'
import {crmStore} from '@CRM/store'

export default defineComponent({
  name: 'CreateOrChange',
  props: {
    title: {
      type: String,
      default: '',
    },
    form: {
      type: Object,
      default: () => {},
    },
  },
  setup(props, context) {
    const validateName = async(rule, value, callback) => {
      if (value === '') {
        callback('请输入市场准入名称')
      } else {
        const name = await validateVEName(value)
        if (name) {
          callback(new Error('市场准入名称已存在'))
        } else {
          callback()
        }
      }
    }
    const api = inject('api')
    const currentInstance = getCurrentInstance()
    var cascader = ref(null)
    var formRef = ref(null)
    var productPopover = ref(null)
    var disabled = ref(false)
    const citys = area
    const props1 = reactive({
      multiple: true,
      expandTrigger: 'hover',
      label: 'regionName',
      value: 'regionCode',
    })
    const modelOptions =
      crmStore.getters['dictionary/getDictionary']['agent_type']
    var appOptions = ref([])
    const priceOptions =
      crmStore.getters['dictionary/getDictionary']['price_type']
    const accessOptions =
      crmStore.getters['dictionary/getDictionary']['access_mode']
    var form = reactive({
      chanceName: '',
      region: [],
      accessMode: '',
      terminalType: '',
      productId: '',
      productName: '',
      producer:'',
      terminalPrice: '',
      priceProperty: '',
      attachFiles: [],
      remark: '',
      expireTime: '',
      chanceNo: '',
      approvalNumber: '',
      packSpecs: '',
      id: '',
      areas: [],
    })
    const validateVEName = async(val) => {
      const pam = {
        table: 'chance_info',
        column: 'chance_name',
        column_data: form.chanceName,
        id: form.id ? form.id : 0,
      }
      const booleName = ref(false)
      const res = await api.common.COMMON_CHECK_UNIQUE(pam)
      if (res.code === 0) {
        if (res.data.exist !== '0') {
          booleName.value = true
        }
      }
      return booleName.value
    }
    var rules = reactive({
      num: [{ required: true, message: '请输入市场准入编号', trigger: 'blur' }],
      chanceName: [
        { required: true, validator: validateName, trigger: 'blur' },
      ],
      accessMode: [
        { required: true, message: '请选择准入模式', trigger: 'change' },
      ],
      areas: [{ required: true, message: '请选择准入地区', trigger: 'change' }],
      termialType: [
        { required: true, message: '请选择适用终端', trigger: 'change' },
      ],
      productName: [
        { required: true, message: '请选择产品', trigger: 'change' },
      ],
      productNum: [
        { required: true, message: '请选择批准文号', trigger: 'change' },
      ],
      packSpecs: [
        { required: true, message: '请选择包装规格', trigger: 'change' },
      ],
      priceProperty: [
        { required: true, message: '请选择价格属性', trigger: 'change' },
      ],
      terminalPrice: [
        { required: true, message: '请输入终端价', trigger: 'blur' },
      ],
      expireTime: [
        { required: true, message: '请选择市场准入结束日期', trigger: 'change' },
      ],
      terminalType: [
        { required: true, message: '请选择适用终端', trigger: 'change' },
      ],
    })
    var dialogForm = reactive({
      // name: '',
      // region: '',
      // remark: ''
    })
    var formLabelWidth = ref(140)
    var dialogShow = ref(false)
    const open = (row) => {
      if (row) {
        form.chanceName = row.chanceName
        form.chanceNo = row.chanceNo
        form.accessMode = row.accessMode
        form.terminalType = row.terminalType
        form.productName = row.productPopularName
        form.productNum = row.approvalNumber
        form.packSpecs = row.packSpecs
        form.producer = row.producer
        form.areas = currentInstance.proxy.getCascaderAreaData(row.region)
        form.region = row.region
        ;(form.terminalPrice = row.terminalPrice),
        (form.priceProperty = String(row.priceProperty))
        form.expireTime = row.expireTime
        form.remark = row.remark
        form.id = Number(row.id)
        form.productId = row.productId
        form.sellUnit = row.sellUnit
        //  row.attachFiles.forEach(item => {
        //       item.Key = item.name
        //       item.Value = item.url
        //     })
        form.attachFiles = row.attachFiles
      }
      dialogShow.value = true
      disabled.value = false
    }
    const close = () => {
      disabled.value = true
      dialogShow.value = false
      form.chanceName = ''
      form.chanceNo = ''
      form.accessMode = ''
      form.terminalType = ''
      form.productName = ''
      form.productNum = ''
      form.producer = ''
      form.packSpecs = ''
      form.areas = []
      form.region = ''
      form.terminalPrice = ''
      form.priceProperty = ''
      form.expireTime = ''
      form.remark = ''
      form.id = ''
      form.productId = ''
      form.attachFiles = []
      formRef.value.clearValidate()
      productPopover.value.onCancel()
    }
    const confirm = () => {
      console.log(props.title)
      if (props.title == '新建市场准入') {
        console.log(11111)
        formRef.value.validate((valid) => {
          if (valid) {
            const data = {
              chanceName: form.chanceName,
              region: form.region,
              accessMode: form.accessMode,
              terminalType: form.terminalType,
              productId: Number(form.productId),
              terminalPrice: Number(form.terminalPrice),
              priceProperty: form.priceProperty,
              attachFiles: form.attachFiles,
              remark: form.remark,
              expireTime: form.expireTime,
            }
            api.chance.CHANCE_CREATE(data).then((res) => {
              if (!res.code) {
                currentInstance.proxy.customMessage({
                  type: 'success',
                  message: '创建成功',
                })
                context.emit('success')
              }
            })
            // context.emit('succsess')
            close()
          } else {
            console.log('error submit!!')
            return false
          }
        })
      } else {
        formRef.value.validate((valid) => {
          if (valid) {
            const data = {
              id: form.id,
              chanceName: form.chanceName,
              region: form.region,
              accessMode: form.accessMode,
              terminalType: form.terminalType,
              productId: Number(form.productId),
              terminalPrice: Number(form.terminalPrice),
              priceProperty: form.priceProperty,
              attachFiles: form.attachFiles,
              remark: form.remark,
              expireTime: form.expireTime,
            }
            api.chance.CHANCE_UPDATE(data).then((res) => {
              if (!res.code) {
                currentInstance.proxy.customMessage({
                  type: 'success',
                  message: '编辑成功',
                })
                context.emit('success')
              }
            })
            // context.emit('succsess')
            close()
          } else {
            console.log('error submit!!')
            return false
          }
        })
      }
    }
    const onInput = () => {}
    const productConfirm = (val) => {
      form.productId = val.id
      form.productName = val.productPopularName
      form.productNum = val.approvalNumber
      form.packSpecs = val.packSpecs
      form.sellUnit = val.sellUnit
      form.producer = val.producer
    }

    const productClear = () => {
      form.productId = 0
      form.productName = ''
      form.approvalNumber = ''
      form.packSpecs = ''
      form.sellUnit = ''
    }

    const priceConfirm = (val) => {
      form.terminalId = val.value.id
      form.app_price = val.value.terminalPrice
      form.terminalPrice = Number(val.value.terminalPrice)
    }

    const priceClear = () => {
      form.terminalId = 0
      form.app_price = ''
      form.terminalPrice = 0
    }

    const areaChange = (val) => {
      console.log(val)

      const serve = currentInstance.proxy.getServeAreaData(
        val,
        cascader.value.getCheckedNodes()
      )
      console.log(serve)
      form.region = serve
      console.log('转换服务器地址 ', serve)
      console.log('转换本地地址 ', currentInstance.proxy.getCascaderAreaData(serve))
    }

    onMounted(() => {
      console.log(props.title, props.form, '=================')
      const a = crmStore.getters['dictionary/getDictionary']['app_mode']
      if (a) {
        appOptions.value = a.slice(1, 4)
      } else {
        appOptions.value =
          crmStore.getters['dictionary/getDictionary']['app_mode']
      }
    })
    return {
      cascader,
      citys,
      props1,
      formRef,
      form,
      rules,
      disabled,
      confirm,
      dialogForm,
      formLabelWidth,
      dialogShow,
      open,
      close,
      modelOptions,
      appOptions,
      priceOptions,
      accessOptions,
      productConfirm,
      productClear,
      priceConfirm,
      priceClear,
      areaChange,
      onInput,
      productPopover,
    }
  },
})
</script>
